package com.second.app.thread.线程基础.day05;

/**
 * @Author GYZ
 * @Date 2023/11/23
 * <pre>
 *  线程死锁：下面这个demo演示了，两个线程互相持有对方锁
 *          导致锁一直没有释放，互相等待。
 *
 * </pre>
 */
public class DeadThread {

    public static void main(String[] args) {
        try {
            Target target = new Target();
            target.setFlag("a");
            Thread thread = new Thread(target);
            thread.start();
            Thread.sleep(100);
            target.setFlag("b");
            Thread thread1 = new Thread(target);
            thread1.start();
        } catch (InterruptedException e) {
           e.printStackTrace();
        }
    }
}
class Target implements Runnable {
    public String userName;

    public final Object lock1 = new Object();

    public final Object lock2 = new Object();

    public void setFlag(String userName) {
        this.userName = userName;
    }

    @Override
    public void run() {
        if(userName.equals("a")){
            synchronized (lock1){
                try {
                    System.out.println("userName ="+userName);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println("按lock1->lock2代码顺序执行了");
                }
            }
        }

        if(userName.equals("b")){
            synchronized (lock2){
                try {
                    System.out.println("userName ="+userName);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println("按lock2->lock1代码顺序执行了");
                }
            }
        }
    }
}
